const router = require('koa-router')()
const strong = require('./lib/set')
const reptile = require('./lib/reptile')
const { checkParms } = require('./lib/parmsCheck')
const db = require('./lib/mysql')
const makeResult = require('./lib/makeResult')

router.prefix('/reptile')

router.get('/', function (ctx, next) {
  let { d, h, log } = strong.get()
  ctx.body = { d, h, log }
})

async function cookieToUser(ctx, power) {
  let token = ctx.cookies.get('token')
  if (!token) return makeResult.fail(ctx, 'token不存在', 304)
  let userInfo = (await db.query(`select * from admin where token=?`, [token]))[0]
  if (userInfo.length == 0) return makeResult.fail(ctx, 'token失效', 304)
  userInfo = userInfo[0]
  if (power && power.indexOf(userInfo.power) == -1) return makeResult.fail(ctx, '权限不足', 304)
  return userInfo
}

router.post('/set', async function (ctx, next) {
  const { d, h } = ctx.request.body
  let checkParmsResulu = checkParms({ d, h }, ctx)
  if (checkParmsResulu != true) return

  let userInfo = await cookieToUser(ctx, [1])
  if (userInfo?.code) return

  let json = strong.get()
  json.d = parseInt(d)
  json.h = parseInt(h)
  strong.set(json)
  reptile.reptile()

  ctx.body = { code: 200, msg: '设置成功' }
})

module.exports = router
